﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lib.Web.Mvc.JQuery.JqGrid;
using jqGrid.JeffSogolov.Models;

namespace jqGrid.JeffSogolov.Controllers
{
    public class HomeController : Controller
    {
        #region Fields
        private IDummyRepository _dummyRepository;
        #endregion

        #region Constructors
        public HomeController()
            : this(new StaticDummyRepository())
        {
        }

        public HomeController(IDummyRepository dummyRepository)
        {
            _dummyRepository = dummyRepository;
        }
        #endregion

        #region Actions
        public ActionResult Dummy()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FindDummy(JqGridRequest request)
        {
            int totalRecordsCount = _dummyRepository.GetCount();

            JqGridResponse response = new JqGridResponse()
            {
                TotalPagesCount = (int)Math.Ceiling((float)totalRecordsCount / (float)request.RecordsCount),
                PageIndex = request.PageIndex,
                TotalRecordsCount = totalRecordsCount
            };
            response.Records.AddRange(from dummy in _dummyRepository.FindRange(String.Format("{0} {1}", request.SortingName, request.SortingOrder), request.PageIndex * request.RecordsCount, request.RecordsCount)
                                      select new JqGridRecord<DummyViewModel>(Convert.ToString(dummy.Id), dummy));

            return new JqGridJsonResult() { Data = response };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult BatchUpdateDummies(List<DummyViewModel> viewModelsBatch)
        {
            foreach (DummyViewModel updatedViewModel in viewModelsBatch)
            {
                DummyViewModel viewModel = _dummyRepository.FindByKey(updatedViewModel.Id);
                viewModel.Updated = updatedViewModel.Updated;
                viewModel.Comparision = updatedViewModel.Comparision;
            }
            return Json(true);
        }

        public ActionResult Comparisions()
        {
            return Content("<select><option value='Equal'>Equal</option><option value='Not equal'>Not equal</option></select>");
        }
        #endregion
    }
}
